
const jwt = require('jsonwebtoken');
const crypto = require('crypto');

const secret = 'nodetest';

// 临时使用md5，目前网上已有破解md5方案了
exports.md5 = password => {
    const hash = crypto.createHash('md5');
    hash.update(password);
    const md5Password = hash.digest('hex');
    return md5Password
}

// 生成token
exports.createToken = id => {
    const token = jwt.sign(
        { id },
        secret, //随便一点内容，加密的密文，私钥对应着公钥
        {
            expiresIn: 60 * 60 //60分钟到期时间
        }
    );
    return token
}

// 解码token
exports.analysisToken = (token) => {
    let id;
    try {
        id = jwt.verify(token, secret).id
    } catch (error) {
        throw Error('token解析错误')
    }
    return id
}